package com.jsj.servlet.ch4;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class ShoppingCarServlet
 */
@WebServlet("/ShoppingCarServlet")
public class ShoppingCarServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		@SuppressWarnings("unused")
		PrintWriter out = response.getWriter();
		
		//获取会话对象
		HttpSession session = request.getSession();
		//从会话域中获取shoppingCar属性对象（即购物车）
		//对象定义为Map类型，key为书名，value为购买数量
		@SuppressWarnings("unchecked")
		Map<String,Integer>car = (Map<String,Integer>)session.getAttribute("shoppingCar");
		//若会话域中无ShoppingCar属性对象，则实例化一个
		if(car == null) {
			car = new HashMap<String,Integer>();
		}
		//获取用户选择的书籍
		String[]books = request.getParameterValues("book");
		if(books!=null && books.length>0) {
			for(String bookName : books) {
				//判断此书籍是否已在购物车中
				if(car.get(bookName)!=null) {
					int num = car.get(bookName);
					car.put(bookName, num + 1);
				}else {
					car.put(bookName, 1);
				}
			}
		}
		//将更新后的购物车存储在会话域中
		session.setAttribute("shoppingCar",car);
		response.sendRedirect("shoppingListServet");
	}
}
